#include "head.h"

int make_child(processData_t *workerList,int childNum)
{
    int i;
    pid_t pid;
    for(i=0;i<childNum;i++)
    {
        int pipefds[2];//管道
        socketpair(AF_LOCAL,SOCK_STREAM,0,pipefds);
        pid=fork();
        //子进程
        if(0==pid)
        {
            close(pipefds[1]);
            handleEvent(pipefds[0]);
        }
        //父进程，保存子进程pid,初始化子进程
        close(pipefds[0]);        
        workerList[i].pid=pid;
        workerList[i].status=FREE;
        workerList[i].pipeFd=pipefds[1];//存储对应子进程管道的对端
#ifdef DEBUG
        printf("workerList[%d].pipeFd=%d\n",i,workerList[i].pipeFd);
#endif
    }
    return 0;
}


//子进程处理任务的函数
int handleEvent(int pipeFd)
{
    int new_fd,finish_flag=1;
    while(1)
    {
        recvFd(pipeFd,&new_fd);
    #ifdef DEBUG
        printf("recv parent task %d\n",new_fd);
    #endif
        transFile(new_fd);
        close(new_fd);
        write(pipeFd,&finish_flag,sizeof(int));
    }
}